<template>
  <div>
    <v-header></v-header>
    <div class="register-content">
      <Tabs value="mobileRegister" :animated="false">
        <TabPane label="手机注册" name="mobileRegister">
          <Form ref="mobileForm" :rules="ruleMobileForm" :model="mobileForm">
            <FormItem prop="mobile">
              <Input v-model="mobileForm.mobile" placeholder="请输入手机号" @on-enter="handleRegister">
              <Icon type="ios-person" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem prop="validCode" inline>
              <Input v-model="mobileForm.validCode" placeholder="请输入验证码" style="width: 50%;"/>
              <Button :disabled="mobileBtnDisabled" @click="getValidatorCode" style="float:right;">{{mobileBtn}}
              </Button>
            </FormItem>
            <FormItem prop="userName">
              <Input v-model="mobileForm.userName" placeholder="请输入用户名" @on-enter="handleRegister">
              <Icon type="ios-person" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" v-model="mobileForm.password" placeholder="请输入密码（字母、数字、至少八位）" @on-enter="handleRegister">
              <Icon type="locked" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem prop="rePassword">
              <Input type="password" v-model="mobileForm.rePassword" placeholder="请再次输入密码（字母、数字、至少八位）"
                     @on-enter="handleRegister">
              <Icon type="locked" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem>
              <Button type="primary" long @click="handleRegister">注册</Button>
            </FormItem>
          </Form>
        </TabPane>
        <TabPane label="邮箱注册" name="emailRegister">
          <Form ref="emailForm" :model="emailForm" :rules="ruleEmailForm">
            <FormItem prop="mobile">
              <Input v-model="emailForm.mobile" placeholder="请输入邮箱号" @on-enter="handleRegister">
              <Icon type="ios-person" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem prop="userName">
              <Input v-model="emailForm.userName" placeholder="请输入用户名" @on-enter="handleRegister">
              <Icon type="ios-person" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" v-model="emailForm.password" placeholder="请输入密码（字母、数字、至少八位）" @on-enter="handleRegister">
              <Icon type="locked" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem prop="rePassword">
              <Input type="password" v-model="emailForm.rePassword" placeholder="请再次输入密码（字母、数字、至少八位）"
                     @on-enter="handleRegister">
              <Icon type="locked" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem inline>
              <Input v-model="emailForm.validCode" placeholder="请输入验证码" style="width: 40%;"/>
              <img width="60" height="32" style="background: skyblue;margin-left: 60px;vertical-align: bottom">
              <a href="#" @click="refreshValidateCode();">换一张</a>
            </FormItem>
            <FormItem>
              <Button type="primary" long @click="handleRegister">注册</Button>
            </FormItem>
          </Form>
        </TabPane>
      </Tabs>
    </div>
    <v-footer></v-footer>
  </div>
</template>

<script>
  import auth from '@/utils/auth'
  import Model from '@/models/apps'
  import header from '@/components/header'
  import footer from '@/components/footer'
  export default {
    name: 'register',
    components: {
      'v-header': header,
      'v-footer': footer
    },
    data () {
      const validateTel = (rule, value, callback) => {
        if (!(/^1[34578]\d{9}$/.test(value))) {
          callback(new Error('手机号码格式不正确'))
        } else {
          callback()
        }
      }
      const validatePassCheck = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.mobileForm.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      const validatePassWord = (rule, value, callback) => {
        if (!/^(?=.*\d.*)(?=.*[a-zA-Z].*).{8,}$/.test(value)) {
          callback(new Error('密码必须包含字母数字，且不少于8位!'))
        } else {
          callback()
        }
      }
      return {
        time: 60,
        mobileBtn: '获取短信验证码',
        mobileBtnDisabled: false,
        mobileForm: {
          userName: '',
          mobile: '',
          password: '',
          rePassword: '',
          validCode: ''
        },
        ruleMobileForm: {
          userName: [
            {
              required: true,
              message: '用户名不能为空'
            }
          ],
          mobile: [
            {
              required: true,
              message: '手机号不能为空'
            },
            {validator: validateTel, trigger: 'blur'}
          ],
          password: [
            {
              required: true,
              message: '密码不能为空'
            },
            {validator: validatePassWord, trigger: 'blur'}
          ],
          rePassword: [
            {
              required: true,
              message: '密码不能为空'
            },
            {validator: validatePassCheck, trigger: 'blur'},
            {validator: validatePassWord, trigger: 'blur'}
          ],
          validCode: [
            {
              required: true,
              message: '短信验证码不能为空'
            }
          ]
        },
        emailForm: {
          username: '',
          password: '',
          rePassword: ''
        },
        ruleEmailForm: {
          mobile: [
            {
              required: true,
              message: '手机号不能为空'
            }
          ],
          password: [
            {
              required: true,
              message: '密码不能为空'
            }
          ],
          rePassword: [
            {
              required: true,
              message: '密码不能为空'
            },
            {validator: validatePassCheck, trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      handleRegister () {
        this.$refs.mobileForm.validate((valid) => {
          if (valid) {
            new Model('mobileRegister')
              .POST({
                params: {
                  ...this.mobileForm
                }
              })
              .then((res) => {
                if (res.data.errorCode === '200') {
                  this.$Message.success('注册成功！！！')
                  this.$router.push('/login')
                } else if (res.data.errorCode === '1002') {
                  this.$Message.error('该手机号已经被注册！！！')
                }
              })
          }
        })
      },
      getValidatorCode () {
        var errorMsg
        this.$refs.mobileForm.validateField('mobile', function (message) {
          errorMsg = message
        })
        if (errorMsg.length !== 0) {
          return
        }
        new Model('sendValidCode')
          .GET({
            params: {
              mobile: this.mobileForm.mobile
            }
          })
          .then((res) => {
            if (res.data.errorCode === '200') {
              this.send()
            } else if (res.data.errorCode === '1002') {
              this.$Message.error('该手机号已经被注册！！！')
            }
          })
      },
      send () {
        let me = this
        me.mobileBtnDisabled = true
        let interval = window.setInterval(function () {
          if ((--me.time) > 0) {
            me.mobileBtn = me.time + '秒后重新发送'
          } else {
            me.time = 60
            me.mobileBtnDisabled = false
            me.mobileBtn = '获取验证码'
            window.clearInterval(interval)
          }
        }, 1000)
      }
    }
  }
</script>

<style>
  .register-content {
    width: 340px;
    margin: 25px auto;
    margin-bottom: 50px;
  }

  .ivu-tabs-nav .ivu-tabs-tab {
    padding: 8px 53px;
  }
</style>
